package org.esk.dablog.gwt.dablog.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.TreeListener;
import org.esk.dablog.gwt.dablog.client.model.ClientForumComment;

/**
 * This class 
 * User: esk
 * Date: 06.01.2007
 * Time: 16:11:21
 * $Id:$
 */
public class ForumCommentSelectionHandler implements TreeItemHandler {

    private int idx;
    private TreeItem onStack;
    private TreeItem dummy = new TreeItem();

    private TreeListener listener = new TreeListener() {

        public void onTreeItemStateChanged(TreeItem item) {
            if (onStack != null) {
                dummy.setHeight(onStack.getOffsetHeight() + "px");
            }
        }

        public void onTreeItemSelected(TreeItem item) {

        }
    };

    private boolean listenerAttached = false;

    public void handle(TreeItem item) {
        if (onStack != null) {
            DOM.setStyleAttribute(onStack.getElement(), "position", "static");
            collapseItem(onStack);
        }
        if(onStack == item) {
            onStack = null;
            dummy.remove();
            return;
        }

        onStack = item;

        if (!listenerAttached) {
            item.getTree().addTreeListener(listener);
        }

        //hacking inside the tree:
        // 1. adding element to the parent's item
        item.getParentItem().addItem(dummy);
        // 2. accessing "child span" of the Tree Item
        Element parentSpan = DOM.getParent(item.getElement());
        // 3. calculating item's actual index
        idx = item.getParentItem().getChildIndex(item);
        // 4. inserting dummy right after the item
        DOM.insertChild(parentSpan, dummy.getElement(), idx + 1);
        // 5. Magnify magic - move the whole subrtee to the left!
        DOM.setStyleAttribute(item.getElement(), "left", "0");
        DOM.setStyleAttribute(item.getElement(), "position", "absolute");
        // 6. Expand item's text
        expandItem(item);
        // 7. updating dummy's height
        dummy.setHeight(item.getOffsetHeight() + "px");
   }

    private void collapseItem(TreeItem item) {
        ForumEntryWidget widget = (ForumEntryWidget) item.getWidget();
        widget.collapse();
    }

    private void expandItem(TreeItem item) {
        ForumEntryWidget widget = (ForumEntryWidget) item.getWidget();
        widget.expand();
    }

}
